﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AutoClick.v1
{
    public static class Config
    {

        public static ConfigModel ConfigModel { get; set; } = new ConfigModel();

        private const string FileName = "config";

        public static void SaveConfig()
        {
            var json = Newtonsoft.Json.JsonConvert.SerializeObject(ConfigModel);
            SaveJson(FileName, json);
        }

        public static void LoadConfig()
        {
            var json = GetJson(FileName);
            ConfigModel = Newtonsoft.Json.JsonConvert.DeserializeObject<ConfigModel>(json) ?? new ConfigModel();
        }

        /// <summary>
        /// 保存JSON数据
        /// </summary>
        /// <param name="filename"></param>
        /// <param name="json"></param>
        private static void SaveJson(string filename, string json)
        {
            try
            {
                var exeFolder = System.Windows.Forms.Application.StartupPath + "\\";
                var directory = exeFolder + "Json\\";
                var filepath = directory + "\\" + filename + ".json";
                if (!Directory.Exists(directory))
                    Directory.CreateDirectory(directory);

                File.WriteAllText(filepath, json);
            }
            catch
            {
                //
            }
        }

        /// <summary>
        /// 获取JSON数据
        /// </summary>
        /// <param name="filename"></param>
        /// <returns></returns>
        private static string GetJson(string filename)
        {
            var res = "";
            try
            {
                var exeFolder = System.Windows.Forms.Application.StartupPath + "\\";
                var directory = exeFolder + "Json\\";
                var filepath = directory + "\\" + filename + ".json";
                // 创建一个 StreamReader 的实例来读取文件 
                // using 语句也能关闭 StreamReader
                using (var sr = new StreamReader(filepath))
                {
                    string line;

                    // 从文件读取并显示行，直到文件的末尾 
                    while ((line = sr.ReadLine()) != null)
                    {
                        res += line;
                    }
                }
            }
            catch
            {

            }
            return res;
        }

    }
}
